package com.xiaozhen.app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.app.OauthClientDetails;
import com.xiaozhen.app.service.SysAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/24 16:05
 * @description:
 */
@RestController
@Api(tags = "Auth2授权管理的接口")
@RequestMapping("/sysAuth")
public class SysAuthController extends BaseController {

    @Autowired
    private SysAuthService sysAuthService;
    @Autowired
    private DiscoveryClient discoveryClient;


    @ApiOperation("获取所有客户端列表")
    @GetMapping("/list")
    public AjaxResult list() {
        Page<OauthClientDetails> page = startPage();
        Page<OauthClientDetails> list = sysAuthService.selectClientList(page);
        return getDataTable(list);
    }

    @ApiOperation("获取所有服务列表")
    @GetMapping("/serviceList")
    public AjaxResult serviceList() {
        List<String> services = discoveryClient.getServices();
        return AjaxResult.success(services);
    }

    @ApiOperation("添加客户端信息")
    @PostMapping("/addSysAuth")
    public AjaxResult addSysAuth(@Validated @RequestBody OauthClientDetails sysAuth) {
        if (!sysAuthService.checkClientIdUnique(sysAuth)) {
            return AjaxResult.error("新增客户端'" + sysAuth.getClientId() + "'失败，客户端ID已存在");
        }
        sysAuth.setCreateBy(getCurrentUserId());
        sysAuth.setCreateTime(LocalDateTime.now());
        return toAjax(sysAuthService.insertSysAuth(sysAuth));
    }

    @ApiOperation("修改客户端信息")
    @PutMapping("/updateSysAuth")
    public AjaxResult updateSysAuth(@Validated @RequestBody OauthClientDetails sysAuth) {
        sysAuth.setUpdateBy(getCurrentUserId());
        sysAuth.setUpdateTime(LocalDateTime.now());
        if (sysAuthService.updateSysAuth(sysAuth) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + sysAuth.getClientId() + "'失败，请联系管理员");
    }

    @ApiOperation("删除客户端信息")
    @DeleteMapping("/{clientIds}")
    public AjaxResult remove(@PathVariable Long[] clientIds) {
        return toAjax(sysAuthService.deleteSysAuthByIds(clientIds));
    }

}
